package com.api.gbhg.huangwm.web;

import com.api.gbhg.huangwm.dao.ReturnReimbursementDao;
import com.customization.commons.LogTool;
import com.engine.common.util.ParamUtil;
import weaver.conn.RecordSet;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2022/04/20
 * @Version 1.0
 * @Description TODO 报销撤单功能-退回所扣减的uf_jingfei,uf_jingfeilaiyuan,以及所属收入预算的金额
 */
@Path("/gb/huangwm/returnBX")
public class ReturnReimbursementApi {
    private ReturnReimbursementDao returnMoney = new ReturnReimbursementDao();
    private LogTool logTool = new LogTool("/log/gbhg/huangwm/web/ReturnReimbursementApi",false);

    @POST
    @Path("/returnMoney")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> returnMoney(@Context HttpServletResponse response, @Context HttpServletRequest request) throws IOException {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus",true);
        Map<String, Object> requestParam = ParamUtil.request2Map(request);
        String requrstid = "";
        if(!requestParam.containsKey("requestid")){
            result.put("apiStatus",false);
            result.put("msg","未接收到请求参数requestid");
            return result;
        }else{
            requrstid = requestParam.get("requestid").toString();
            if(requrstid.isEmpty()){
                result.put("apiStatus",false);
                result.put("msg","请求参数requestid为空");
                return result;
            }
        }
        boolean isReturn = (boolean) requestParam.getOrDefault("isReturn",true);
        Map<String,String> requrstInfo = returnMoney.getRequrstInfo(requrstid);
        boolean uf_jingfei = false,uf_jingfeilaiyuan = false,shouruyusuan = false;
        if(requrstInfo==null){
            result.put("apiStatus",false);
            result.put("msg","获取requrstInfo为空,请检查参数是否正确");
            return result;
        }else{
            if(!requrstInfo.get("currentnodetype").equals("3")){
                result.put("apiStatus",false);
                result.put("msg","当前流程["+requrstid+"]未归档结束请勿通过此功能撤单");
                return result;
            }
            try{
                List<Map<String,String>> requestData = returnMoney.getRequestData(requrstInfo);
                if(requestData.size()<=0){
                    result.put("apiStatus",false);
                    result.put("msg","获取流程数据为空");
                    return result;
                }
                uf_jingfei = returnMoney.uf_jingfei(requestData,true);
                if(uf_jingfei){
                    uf_jingfeilaiyuan = returnMoney.uf_jingfeilaiyuan(requestData,true);
                    if(uf_jingfeilaiyuan){
                        shouruyusuan = returnMoney.shouruyusuan(requestData,true);
                        if(shouruyusuan){
                            returnMoney.deleteRecords(requrstid);
                        }else{
                            //shouruyusuan释放失败时回滚uf_jingfeilaiyuan
                            returnMoney.uf_jingfeilaiyuan(requestData,false);
                            result.put("apiStatus",false);
                            result.put("msg","释放收入预算失败,请联系管理员查看日志");
                            return result;
                        }
                    }else{
                        //uf_jingfeilaiyuan释放失败时回滚uf_jingfei
                        returnMoney.uf_jingfei(requestData,false);
                        result.put("apiStatus",false);
                        result.put("msg","释放uf_jingfeilaiyuan失败,请联系管理员查看日志");
                        return result;
                    }
                }else{
                    result.put("apiStatus",false);
                    result.put("msg","释放uf_jingfei失败,请联系管理员查看日志");
                    return result;
                }
                result.put("uf_jingfei",uf_jingfei);
                result.put("uf_jingfeilaiyuan",uf_jingfeilaiyuan);
                result.put("shouruyusuan",shouruyusuan);
            }catch (Exception e){
                e.printStackTrace();
                result.put("apiStatus",false);
                result.put("msg","撤单返还报销金额失败;"+e.getMessage());
                return result;
            }
        }
        returnMoney.updateRecord(requrstid,requrstInfo.get("firstnodeid"));

        //执行流程干预参数
        Map<String, Object> doIntervenorParams = new HashMap<>();
        doIntervenorParams.put("requestId",Integer.parseInt(requrstid));
        //干预指向的节点id 默认为发起节点
        doIntervenorParams.put("submitNodeId",Integer.parseInt(requrstInfo.get("firstnodeid")));
        //干预的接收人 默认为发起人
        doIntervenorParams.put("Intervenorid",requrstInfo.get("creater"));
        doIntervenorParams.put("remark","报销撤单");
        //不再调用发起的节点前附加操作防止重复释放
        doIntervenorParams.put("enableIntervenor",false);
        doIntervenorParams.put("SignType",0);
        result.put("doIntervenorParams",doIntervenorParams);
//        List<NameValuePair> nvps = new ArrayList();
//        if(doIntervenorParams!=null){
//            for (Map.Entry<String,Object> entry : doIntervenorParams.entrySet()) {
//                nvps.add(new BasicNameValuePair(entry.getKey(), JSONObject.toJSONString(entry.getValue())));
//            }
//        }
//        CloseableHttpResponse crespose;// 响应类,
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        //接口url
//        HttpPost httpPost = new HttpPost("http://39.98.117.174:4011/api/workflow/paService/doIntervenor");
//        try{
//            httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
//            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
//
//            crespose = httpClient.execute(httpPost);
//            if (crespose != null && crespose.getEntity() != null) {
//                String res = EntityUtils.toString(crespose.getEntity());
//                //todo这里处理返回信息
//                result.put("apiStatus",true);
//                result.put("doIntervenor",res);
//            }else{
//                //干预失败是否再次退还已释放的额度？
//                result.put("apiStatus",false);
//                result.put("msg","请求干预接口未返回内容");
//                return result;
//            }
//        }catch (Exception e){
//            result.put("apiStatus",false);
//            result.put("msg",e.getMessage());
//            return result;
//        }
        return result;
    }

    @GET
    @Path("/hasRight")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> hasRight(@Context HttpServletResponse response, @Context HttpServletRequest request) throws IOException {
        Map<String, Object> result = new HashMap<>();
        User user = HrmUserVarify.getUser(request, response);
        if(user == null){
            result.put("hasRight",false);
            result.put("msg","未获取到当前用户信息");
            return result;
        }
        Map<String, Object> requestParam = ParamUtil.request2Map(request);
        String requrstid = "";
        if(!requestParam.containsKey("requestid")){
            result.put("apiStatus",false);
            result.put("msg","未接收到请求参数requestid");
            return result;
        }else{
            requrstid = requestParam.get("requestid").toString();
            if(requrstid.isEmpty()){
                result.put("apiStatus",false);
                result.put("msg","请求参数requestid为空");
                return result;
            }
        }
        RecordSet rs = new RecordSet();
        rs.execute("select * from HrmRoleMembers where roleid=80 and resourceid="+user.getUID());
        if(rs.next()){
            //查询当前用户是否在会计审核环节出现过
            try {
                result.put("hasRight",returnMoney.isOperatorKj(requrstid,user.getUID()));
                result.put("msg","");
            } catch (Exception e) {
                result.put("hasRight",false);
                result.put("msg",e.getMessage());
            }
        }else{
            result.put("hasRight",false);
            result.put("msg","当前用户不在会计角色中");
        }
        return result;
    }
}
